<!--
  Copyright 2019 Hackware SpA <human@hackware.cl>
  This file is part of "Hackware Userland" and licensed under the terms
  of the GNU Affero General Public License version 3, or (at your option)
  a later version. You should have received a copy of this license along
  with the software. If not, see <https://www.gnu.org/licenses/>.
-->

<template>
  <div class="transactions">
    <h2>Mis transacciones</h2>
    <table>
      <thead>
        <tr>
          <th>Estado</th>
          <th>Emisión</th>
          <th>Descripción</th>
          <th>Monto</th>
          <th>Balance</th>
        </tr>
      </thead>
      <tbody
        v-for="transaction in transactions"
        :key="transaction.id"
      >
        <tr :class="`status-${transaction.status}`">
          <td>
            <i :class="statusIcon(transaction.status)" />
            <template v-if="transaction.status === 'ok'">
              {{ okWord() }}
            </template>
            <template v-else-if="transaction.status === 'due'">
              expira el {{ transaction.due_at | date }}
            </template>
            <template v-else>
              expiró el {{ transaction.due_at | date }}
            </template>
          </td>
          <td>{{ transaction.created_at | datetime }}</td>
          <td>{{ transaction.description }}</td>
          <td>{{ transaction.amount | currency }}</td>
          <td>{{ transaction.balance | currency }}</td>
        </tr>
      </tbody>
    </table>
    <VPagination
      v-if="totalPages"
      :total-pages="totalPages"
    />
  </div>
</template>

<script>
import VPagination from '@/components/VPagination.vue';

export default {
  name: 'Transactions',
  components: {
    VPagination,
  },
  data() {
    return {
      transactions: [],
      totalPages: null,
    };
  },
  created() {
    const page = ('page' in this.$route.query) ? Number(this.$route.query.page) : 1;
    this.fetchTransactions(page);
  },
  methods: {
    statusIcon(status) {
      let icon;
      switch (status) {
        case 'ok':
          icon = 'fas fa-check-circle';
          break;
        case 'due':
          icon = 'fas fa-exclamation-triangle';
          break;
        case 'expired':
          icon = 'fas fa-skull-crossbones';
          break;
        default:
          icon = 'fas fa-question';
      }
      return icon;
    },
    okWord() {
      const words = [
        'cachi lupis', 'picho caluga', 'súper', 'OK', 'todo bien', 'no problemo',
      ];
      return words[Math.floor(Math.random() * words.length)];
    },
    determineStatus(dueAt) {
      if (!dueAt) return 'ok';

      const dueDate = new Date(dueAt);
      const currentDate = new Date();
      if (currentDate.getTime() < dueDate.getTime()) return 'due';
      return 'expired';
    },
    fetchTransactions(page) {
      this.$fetcher.haweseGet('/transactions', {
        user_uid: this.$auth.uid,
        page,
        limit: 10,
        sort: '-id',
      })
        .then((body) => {
          this.totalPages = body.meta.total_pages;
          this.transactions = body.data.map((transaction) => {
            const editedTransaction = transaction;
            editedTransaction.status = this.determineStatus(transaction.due_at);
            return editedTransaction;
          });
        });
    },
  },
  beforeRouteUpdate(to, from, next) {
    if (to.name === 'transactions') {
      this.fetchTransactions(to.query.page);
    }

    next();
  },
};
</script>

<style lang="scss">
@import "../assets/bootstrap/custom";

.transactions {
  @extend .pt-3;
  > table {
     @extend .table;
     @extend .table-hover;
     @extend .table-borderless;
     @extend .table-striped;

    >tbody > tr {
      // &.status-ok { }
      &.status-due {
        @extend .table-warning;
      }
      &.status-expired {
        @extend .table-danger;
      }
    }
  }
}
</style>
